﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SZHelperCore.CryptoHelpers
{
    /// <summary>
    /// 数据加密标准 - Data Encryption Standard（DES）
    /// </summary>
    public class DesCryptoUtil
    {
        readonly byte[] key;
        readonly byte[] iv;
        readonly Encoding encoding;
        public DesCryptoUtil(string key, string iv) : this(key, iv, Encoding.UTF8)
        {
        }
        public DesCryptoUtil(string key, string iv, Encoding encoding)
        {
            this.key = Convert.FromBase64String(key);
            this.iv = Convert.FromBase64String(iv);
            this.encoding = encoding;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainTxt">要加密的文字</param>
        /// <returns>Base64 编码的密文</returns>
        public string Encrypt(string plainTxt)
        {
            using var des = DES.Create(); // ✅ 推荐方式：无参 Create()
            using var memoryStream = new MemoryStream();
            using var cryptoStream = new CryptoStream(
                memoryStream,
                des.CreateEncryptor(key, iv),
                CryptoStreamMode.Write);

            var plainBytes = encoding.GetBytes(plainTxt);
            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
            cryptoStream.FlushFinalBlock();

            return Convert.ToBase64String(memoryStream.ToArray());
        }
        public string Decrypt(string cipherTxt)
        {
            using var des = DES.Create(); // ✅
            using var memoryStream = new MemoryStream(Convert.FromBase64String(cipherTxt));
            using var cryptoStream = new CryptoStream(
                memoryStream,
                des.CreateDecryptor(key, iv),
                CryptoStreamMode.Read);

            using var reader = new StreamReader(cryptoStream, encoding);
            return reader.ReadToEnd();
        }
    }
}
